package com.dingwen.treasure.mybatisplus.listener;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.dingwen.treasure.mybatisplus.util.JavaScriptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 　RuleCacheListener: 通过redis订阅发布实现缓存刷新
 * 　@author dingwen
 * 　@date 2022/6/3
 */
@Slf4j
@Component
public class RuleCacheListener extends MessageListenerAdapter implements MessageListener {

    /**
     * 系统配置工具
     */
    @Resource
    private JavaScriptUtil javaScriptUtil;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] body = message.getBody();
        if (body.length > 0) {
            String data = new String(body);
            JSONArray objects = JSONUtil.parseArray(data);
            // 传递的数据类型
            String type = String.valueOf(objects.get(0));
            // 传递的值
            final Object value = objects.get(1);
            log.info("收到来自redis到缓存刷新，数据类型为：{},正在执行本地缓存刷新：{}", type, value);
            javaScriptUtil.refreshLocalCache(JSONUtil.toBean(value.toString(), Map.class));
        }
    }
}
